package com.atguigu.gulimall.search.thread;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.AbstractQueuedSynchronizer;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;

/**
 * @ ClassName MyLock
 * @ Description TODO
 * @ Author admin
 * @ Date 2021/3/17 11:30
 * @ Version 1.0
 */
public class MyLock implements Lock {

    private DiyLock diyLock = new DiyLock();


    static class DiyLock extends AbstractQueuedSynchronizer {

        /**
         * 7         * Creates a new {@code AbstractQueuedSynchronizer} instance
         * 8         * with initial synchronization state of zero.
         * 9
         */


        protected DiyLock() {
            super();

        }


        //获取锁
        @Override
        protected boolean tryAcquire(int arg) {

            //1.获取状态
            int state = getState();

            if (state == 0) {
                //利用CAS原理修改state
                if (compareAndSetState(0, arg)) {
                    //可以修改，则设置当前线程占有资源
                    setExclusiveOwnerThread(Thread.currentThread());
                    return true;
                }

            } else if (getExclusiveOwnerThread() == Thread.currentThread()) {
                //当前线程重入
                setState(getState() + arg);
                return true;
            }
            //获取失败
            return false;
        }

        //释放锁
        @Override
        protected boolean tryRelease(int arg) {
            int state = getState() - arg;

            //判断释放后是否为0
            if (state == 0) {
                //释放当前占有线程
                setExclusiveOwnerThread(null);
                setState(state);
                return true;
            }
            setState(state);//重入性问题
            return false;
        }

        public Condition newCondtionObject() {
            return new ConditionObject();

        }

    }

    @Override
    public void lock() {

    }

    @Override
    public void lockInterruptibly() throws InterruptedException {

    }

    @Override
    public boolean tryLock() {
        return false;
    }

    @Override
    public boolean tryLock(long time, TimeUnit unit) throws InterruptedException {
        return false;
    }

    @Override
    public void unlock() {

    }

    @Override
    public Condition newCondition() {
        return null;
    }
}
